import { Component, OnInit } from '@angular/core';
import { NbWindowRef, NbWindowService } from '@nebular/theme';
import { CheckWeekdayComponent } from '../check-weekday/check-weekday.component';
import { HttpHelper } from '../../Helper/HttpHelper';
import { DtoResultObj } from 'src/app/Model/DtoRec/DtoResult';
import { LocalDataSource } from 'src/app/Lib/ng2-smart-table/public-api';
import { DtoSaveObj } from 'src/app/Model/DtoPost/DtoSaveObj';
import { Fun } from 'src/app/Config/Fun';

@Component({
  selector: 'app-teacher-cfg',
  templateUrl: './teacher-cfg.component.html'
})
export class TeacherCfgComponent implements OnInit {
  buttons = []
  bean = {
    "teacher_id": 0,
    "name": "",
    "no_course": "",
    "courseList": [
      {
        "teacher_course_id": 0,
        "teacher_id": 0,
        "course_id": 0,
        "place_id": 0,
        "together_num": 0
      }
    ],
  }
  screenheight: number = document.documentElement.clientHeight - 300
  screenWidth: number = document.documentElement.clientWidth * 0.8
  PlaceList: any[] = [];
  CourseList: any[] = [];

  //选中的课程列表
  CheckCourseList = [];

  //用于加载设置，如果为 false，则不显示Table,
  LoadSetting: boolean = false;
  settings = {
    noDataMessage: "无数据",
    mode: "inline",
    selectMode: 'single', // single|multi
    // hideHeader: true,
    hideSubHeader: true, //隐藏筛选行
    actions: {
      columnTitle: "操作",
      add: false,
      delete: false,
      position: 'left'
      // position:"right"
    },
    add: {
      addButtonContent: '添加',
      createButtonContent: '创建',
      cancelButtonContent: '取消',
    },
    edit: {
      editButtonContent: '编辑',
      saveButtonContent: '确定',
      cancelButtonContent: '取消',
    },
    delete: {
      deleteButtonContent: '删除',
      confirmDelete: true,
    },
    columns: {
      course_id: {
        title: '科目',
        type: 'number',
        editable: false,
        valuePrepareFunction: (v) => { return this.formartCourseName(v) }
      },
      place_id: {
        title: '地点',
        type: 'string',
        editable: true,
        valuePrepareFunction: (v) => { return this.formartPlaceName(v) },
        editor: {
          type: "list",
          config: {
            list: []
          }
        }
      },
      no_course: {
        title: '不排课时间（21：表示周1第2节,多节用,号分开）',
        type: 'number',
        editable: true
      },
      together_num: {
        title: '连排次数',
        type: 'number',
        editable: true
      }
    },
  };

  //星期
  weekDay: any = {};

  source: LocalDataSource = new LocalDataSource();
  constructor(
    private windowService: NbWindowService,
    public windowRef: NbWindowRef,
    private HttpHelper: HttpHelper,
  ) {
    // this.bean=this.windowRef.config.context;
  }

  formartCourseName(id) { 
    if (this.CourseList != null) {
      for (let index = 0; index < this.CourseList.length; index++) {
        const element = this.CourseList[index];
        if (element.id == id) {
          return element.name;
        }
      }
    }
    return id;
  }

  formartPlaceName(id) {
    if (this.PlaceList != null) {
      for (let index = 0; index < this.PlaceList.length; index++) {
        const element = this.PlaceList[index];
        if (element.value == id) {
          return element.title;
        }
      }
    }
    return id;
  }

  ngOnInit(): void {
    //从query传过来的实体
    console.log(this.bean)
    if (this.bean.no_course != null && this.bean.no_course != "") {
      this.bean.no_course.split(',').forEach(element => {
        this.weekDay["key_" + element] = true;
      });
    }


    this.HttpHelper.Post("Public/PlaceList", null).then((data: DtoResultObj<any>) => {
      if (data.success) {
        this.PlaceList = [{ value: "", title: "" }];
        data.dataList.forEach(element => {
          this.PlaceList.push({ value: parseInt(element.id), title: element.name })
        });
        this.settings.columns.place_id.editor.config.list = this.PlaceList;
        this.LoadSetting = true;
      }
    }, (x) => {
      console.log(x)
    })

    this.HttpHelper.Post("Public/CourseList", null).then((data: DtoResultObj<any>) => {
      if (data.success) {
        this.CourseList = data.dataList;

        if (this.bean.courseList == null) {
          this.bean.courseList = [];
        }
        this.bean.courseList.forEach(element => {
          this.CheckCourseList["key_" + element.course_id] = true;
        });

        // this.settings.columns.course_id.editor.config.list = this.CourseList;

      }
    }, (x) => {
      console.log(x)
    })

  }


  checkNoCourse() {
    this.windowService.open(CheckWeekdayComponent, {
      closeOnBackdropClick: false,
      windowClass: "DivWindow",
      title: "选择",
      context: {
        buttons: [
          {
            name: "确定", click: (x) => {
              return new Promise(async (resolve, reject) => {
                console.log(x);
                resolve({});
              });
            }
          }]
      }
    });
  }

  ButtonClick(even) {

    let list = [];
    for (const key in this.weekDay) {
      const element = this.weekDay[key];
      if (this.weekDay[key]) {
        list.push(key.replace("key_", ""));
      }
    }
    this.bean.no_course = list.join(",");

    even(Fun.ClearNull(this.bean))
      .then((x: DtoResultObj<any>) => {
        console.log(x)
        if (x.success) {
          this.windowRef.close();
        }
      })
  }

  changeTab($event: any) {
    if ($event.tabId == 3) {
      if (this.bean.courseList == null) this.bean.courseList = [];
      //删除不存在的
      for (let index = 0; index < this.bean.courseList.length; index++) {
        const element = this.bean.courseList[index];
        let isexist = false;

        for (const key in this.CheckCourseList) {
          if (this.CheckCourseList[key]) {
            let id = parseInt(key.replace("key_", ""));
            if (element.course_id == id) {
              isexist = true;
              break;
            }
          }
        }
        if (!isexist) {
          this.bean.courseList.splice(index, 1);
          console.log(this.bean.courseList);
        }
      }

      //添加选中的
      for (const key in this.CheckCourseList) {
        if (this.CheckCourseList[key]) {
          let id = parseInt(key.replace("key_", ""));
          let isexist = false;

          for (let index = 0; index < this.bean.courseList.length; index++) {
            const element = this.bean.courseList[index];
            if (element.course_id == id) {
              isexist = true;
              break;
            }
          }
          if (!isexist) {
            this.bean.courseList.push({
              "teacher_course_id": 0,
              "teacher_id": this.bean.teacher_id,
              "course_id": id,
              "place_id": 0,
              "together_num": 0
            })
          }
        }
      }
      this.source.load(this.bean.courseList);
    }
  }

}
